<template>
  <uni-popup ref="popupRef" type="bottom" background-color="#fff">
    <view class="date-picker-modal">
      <view class="modal-header">
        <text class="header-btn" @click="handleReset">重置</text>
        <text class="modal-title">月份选择</text>
        <text class="header-btn confirm" @click="handleConfirm">确定</text>
      </view>
      <picker-view
        :value="pickerValue"
        @change="pickerChange"
        class="picker-view"
      >
        <picker-view-column>
          <view class="picker-item" v-for="(year, index) in years" :key="index">
            {{ year }}年
          </view>
        </picker-view-column>
        <picker-view-column>
          <view
            class="picker-item"
            v-for="(month, index) in months"
            :key="index"
          >
            {{ month }}月
          </view>
        </picker-view-column>
      </picker-view>
    </view>
  </uni-popup>
</template>

<script setup>
import { ref, computed } from "vue";
import dayjs from "dayjs";

// Props
const props = defineProps({
  currentYear: {
    type: Number,
    default: () => dayjs().year(),
  },
  currentMonth: {
    type: Number,
    default: () => dayjs().month() + 1,
  },
});

// Emits
const emit = defineEmits(["confirm"]);

// 弹窗引用
const popupRef = ref(null);

// 获取当前年月
const now = dayjs();
const currentYear = now.year();
const currentMonth = now.month() + 1; // dayjs的月份是0-11，需要+1

// 生成年份数组（从5年前到当前年，从小到大排列）
const years = computed(() => {
  const yearArray = [];
  for (let i = currentYear - 5; i <= currentYear; i++) {
    yearArray.push(i);
  }
  return yearArray;
});

// picker-view 的值（默认选中当前年月，当前年在数组最后）
const pickerValue = ref([5, currentMonth - 1]); // 5是当前年的索引（数组长度6，索引0-5）

// 当前选中的年份索引（默认为当前年，即数组最后一个）
const selectedYearIndex = ref(5);

// 生成月份数组（根据选中的年份动态生成）
const months = computed(() => {
  const selectedYear = years.value[selectedYearIndex.value];
  const monthArray = [];

  // 如果选中的是当前年，只能选择到当前月
  if (selectedYear === currentYear) {
    for (let i = 1; i <= currentMonth; i++) {
      monthArray.push(i);
    }
  } else {
    // 历史年份可以选择全部12个月
    for (let i = 1; i <= 12; i++) {
      monthArray.push(i);
    }
  }

  return monthArray;
});

// 打开弹窗
const open = () => {
  // 同步当前日期到 picker
  const yearIndex = years.value.findIndex((year) => year === props.currentYear);
  const monthIndex = props.currentMonth - 1;

  selectedYearIndex.value = yearIndex !== -1 ? yearIndex : 0;

  // 确保月份索引在有效范围内
  const validMonthIndex = Math.min(monthIndex, months.value.length - 1);
  pickerValue.value = [selectedYearIndex.value, Math.max(0, validMonthIndex)];

  popupRef.value.open();
};

// 关闭弹窗
const close = () => {
  popupRef.value.close();
};

// picker 值改变
const pickerChange = (e) => {
  const newValue = e.detail.value;
  const oldYearIndex = selectedYearIndex.value;
  const newYearIndex = newValue[0];

  // 如果年份改变了
  if (oldYearIndex !== newYearIndex) {
    selectedYearIndex.value = newYearIndex;

    // 检查当前选中的月份在新年份下是否有效
    const newMonths = months.value;
    const currentMonthIndex = newValue[1];

    // 如果当前月份索引超出了新年份的月份范围，重置为最后一个月
    if (currentMonthIndex >= newMonths.length) {
      pickerValue.value = [newYearIndex, newMonths.length - 1];
    } else {
      pickerValue.value = newValue;
    }
  } else {
    pickerValue.value = newValue;
  }
};

// 重置
const handleReset = () => {
  close();
};

// 确认
const handleConfirm = () => {
  const selectedYear = years.value[pickerValue.value[0]];
  const selectedMonth = months.value[pickerValue.value[1]];

  if (selectedYear && selectedMonth) {
    emit("confirm", {
      year: selectedYear,
      month: selectedMonth,
    });
  }

  close();
};

// 暴露方法
defineExpose({
  open,
  close,
});
</script>

<style lang="scss" scoped>
.date-picker-modal {
  background-color: #fff;
  border-radius: 20rpx 20rpx 0 0;
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 40rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.header-btn {
  font-size: 28rpx;
  color: #999;

  &.confirm {
    color: #ffb200;
  }
}

.modal-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
}

.picker-view {
  height: 400rpx;
  padding: 0 40rpx;
}

.picker-item {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 68rpx;
  font-size: 32rpx;
  color: #333;
}
</style>
